﻿
function NodeData(id, text, state, children) {
    this.id = id;
    this.text = text;
    this.state = state;
    this.children = children;
}

function SharedDocument(documentRowId, icon, fileName, author, lastModifyDate, fileSize, isCreatedByMe, authorId, fileUrl) {
    this.documentRowId = documentRowId;
    this.fileName = fileName;
    this.author = author;
    this.lastModifyDate = lastModifyDate;
    this.fileSize = fileSize;
    this.isCreatedByMe = isCreatedByMe;
    this.authorId = authorId;
    this.icon = icon;
    this.fileUrl = fileUrl;
}

var defaultState = {
   'opened': true
}

$(document).ready(function () {
    LoadLibraryTree();
    LoadContentMenu();
    SP.SOD.executeFunc("sp.js", "SP.ClientContext", RefreshDataForSharedSpace);

    var searchIconForSharedSpace = document.getElementById("SearchIconForSharedSpace");
    searchIconForSharedSpace.onclick = SearchSharedSpaceDocuments;

    var shareSpaceUploadFile = document.getElementById("ShareSpaceUploadFile");
    shareSpaceUploadFile.onclick = UpLoadSharedDocument;

    $("#SearchInputForShareSpace").keyup(function (e) {
        if (e.keyCode == 13) {           
            SearchSharedSpaceDocuments();
        }
    });
});

function UpLoadSharedDocument()
{    var uploadUrl = globalConfig.documentUpLoadUrl;
    if (globalConfig.currentDocumentFolder && globalConfig.currentDocumentFolder != "root") {
        uploadUrl = uploadUrl.replace("RootFolder=", "RootFolder=" + encodeURI(globalConfig.currentDocumentFolder));       
    }

    openDialogForSharedDocument(uploadUrl, "上传文档");
}

function openDialogForSharedDocument(url, title) {
    var options = {
        url: url,
        width: 600,
        height: 320,
        title: title,
        dialogReturnValueCallback: CallBackfromUploadSharedDocumentDialog
    };

    SP.UI.ModalDialog.showModalDialog(options);
}

function CallBackfromUploadSharedDocumentDialog(dialogResult) {
    if (dialogResult == 1) {
        // TBD：refresh the data
        RefreshDataForSharedSpace(); // defined in MeetingRecords.js
    }
    else {
        // Do nothing
    }
}

    function LoadLibraryTree() {      

        // Attach the dynatree widget to an existing <div id="tree"> element
        // and pass the tree options as an argument to the dynatree() function:
        /*$("#jstree").dynatree({
          onActivate: function(node) {
            // A DynaTreeNode object is passed to the activation handler
            // Note: we also get this event, if persistence is on, and the page is reloaded.
            alert("You activated " + node.data.title);
          },
          children: [
            {title: "Item 1"},
            {title: "Folder 2", isFolder: true, key: "folder2",
              children: [
                {title: "Sub-item 2.1"},
                {title: "Sub-item 2.2"}
              ]
            },
            {title: "Item 3"}
          ]
        });*/ 
   
        // http://sharepoint2010/SDQ1E31Q/_layouts/hzWeb/GetLibraryTree.ashx?ListName=Documents

        $.ajax({
            type: "GET",
            url: globalConfig.LibraryTreeJosnUrl,
            dataType: "json",
            success: function (data) {
                $("#SharePaceLibraryTree").dynatree({
                    minExpandLevel: 1,
                    onActivate: function (node) {
                        globalConfig.currentDocumentFolder = node.data.key;
                        $("#SearchInputForShareSpace").val("");
                        RefreshDataForSharedSpace();
                    },
                    children: data
                });
            }
        });
    }

    var shareSpaceDocuments;

    function RefreshDataForSharedSpace(isSearch, searchText) {
        var sharedSpaceBusy = document.getElementById("SharedSpaceBusy");
        sharedSpaceBusy.classList.remove("hidden");

        var sharedSpaceTable = document.getElementById("SharedSpaceTable");
        sharedSpaceTable.classList.add("hidden");

        var clientContext = new SP.ClientContext();
        var web = clientContext.get_web();
        var camlQuery = new SP.CamlQuery();
        var where = "";
        var lastSearchLink = document.getElementById("LastSearchLink");
        if (isSearch) {                   
            if (searchText) {
                globalConfig.sharedDocumentsSearchText = searchText;
                where = "<Where> <And>" +
                          "<Contains>" +
                          "<FieldRef Name='LinkFilename' />" +
                          "<Value Type='Text'>" + searchText.Trim() + "</Value>" +
                        "</Contains>" +
                        "<IsNotNull> <FieldRef Name='File_x0020_Size' /></IsNotNull>" +
                        "</And></Where>";
            }

            lastSearchLink.classList.add("SelectedSearchLink");
        }
        else {
            lastSearchLink.classList.remove("SelectedSearchLink");
            where = "<Where><IsNotNull> <FieldRef Name='File_x0020_Size' /></IsNotNull></Where>";
            if (globalConfig.currentDocumentFolder != "root") {
                camlQuery.set_folderServerRelativeUrl(globalConfig.currentDocumentFolder);
            }          
        }

        var scope = "FilesOnly";
        if (isSearch) {
            scope = "RecursiveAll";
        }

        var viewXml = '<View Scope="'+scope+'" RecurrenceRowset="TRUE">' +
            "<Query>"
                   + where + "<OrderBy><FieldRef Name='Last_x0020_Modified' Ascending='TRUE' /></OrderBy></Query><RowLimit>10000</RowLimit>" +
            "</View>";
        camlQuery.set_viewXml(viewXml);
        shareDocument = clientContext.get_web().get_lists().getByTitle(globalConfig.shareDocumentsName);
        shareSpaceDocuments = shareDocument.getItems(camlQuery);

        clientContext.load(shareSpaceDocuments, 'Include(Id,Author,DocIcon,Last_x0020_Modified,LinkFilename,FileSizeDisplay,FileRef)');
        clientContext.executeQueryAsync(successHandlerForQuerySharedDocuments, onFailureForQuerySharedDocuments);
    }

    function successHandlerForQuerySharedDocuments() {
        var itemsEnumerator = shareSpaceDocuments.getEnumerator();
        var itemCount = 0;        
        globalConfig.SharedDocuments = new ShareDocuments();
        while (itemsEnumerator.moveNext()) {
            var currentItem = itemsEnumerator.get_current();
            var currentDocument = new SharedDocument();
            currentDocument.documentRowId = currentItem.get_id();
            currentDocument.fileName = currentItem.get_item("LinkFilename");
            currentDocument.fileUrl = currentItem.get_item("FileRef");
            currentDocument.author = currentItem.get_item("Author").get_lookupValue();
            currentDocument.authorId = currentItem.get_item("Author").get_lookupId();
            currentDocument.fileSize = (currentItem.get_item("FileSizeDisplay") / (1024 * 1024.0)).toFixed(2) + "MB";
            currentDocument.icon = currentItem.get_item("DocIcon");
            currentDocument.lastModifyDate = currentItem.get_item("Last_x0020_Modified").substr(0, 10).replace(/-/g, "\/");                       
            globalConfig.SharedDocuments.documents.push(currentDocument);            
            itemCount++;
        }

        globalConfig.SharedDocuments.totalRecords = itemCount;
        globalConfig.SharedDocuments.currentPage = 1;
        globalConfig.SharedDocuments.startIndex = 0;
        if (globalConfig.SharedDocuments.totalRecords >= globalConfig.SharedDocuments.recordPageSzie) {
            globalConfig.SharedDocuments.endIndex = globalConfig.SharedDocuments.recordPageSzie - 1;
        }
        else {
            globalConfig.SharedDocuments.endIndex = globalConfig.SharedDocuments.totalRecords - 1;
        }

        RenderSharedDocuments();

        var sharedSpaceBusy = document.getElementById("SharedSpaceBusy");
        sharedSpaceBusy.classList.add("hidden");

        var sharedSpaceTable = document.getElementById("SharedSpaceTable");
        sharedSpaceTable.classList.remove("hidden");

        var previousPageForSharedSpace = document.getElementById("PreviousPageForSharedSpace");
        previousPageForSharedSpace.onclick = SharedDocumentPreviousPage;

        var nextPageForSharedSpace = document.getElementById("NextPageForSharedSpace");
        nextPageForSharedSpace.onclick = SharedDocumentNextPage;
    }

    function SharedDocumentPreviousPage() {
        if (globalConfig.SharedDocuments && globalConfig.SharedDocuments.canMovePreviousPage()) {
            globalConfig.SharedDocuments.movePreviousPage();
            RenderSharedDocuments();
        }
        else {
            alert("没有上一页了!");
        }
    }


    function SharedDocumentNextPage() {
        if (globalConfig.SharedDocuments && globalConfig.SharedDocuments.canMoveNextPage()) {
            globalConfig.SharedDocuments.moveNextPage();
            RenderSharedDocuments();
        }
        else {
            alert("没有下一页了!");
        }
    }
    var sharedSpaceMenu;
    function RenderSharedDocuments() {
        var sharedDocumentTable = document.getElementById("SharedSpaceTable");
        ClearRowInTable("SharedSpaceTable");
        for (var index = globalConfig.SharedDocuments.startIndex; index <= globalConfig.SharedDocuments.endIndex; index++) {
            var record = globalConfig.SharedDocuments.documents[index];            
            CreateSharedDocumentRow(record, sharedDocumentTable);
        }

        var sharedSpaceMenu = [{
            name: '下载',
            title: '下载',
            fun: function (e) {
                e.currentTarget.parentNode.style.display = "none";
                SharedDocumentOpenRow();
            }
        }, {
            name: '编辑',
            title: '编辑',
            fun: function (e) {
                e.currentTarget.parentNode.style.display = "none";
                SharedDocumentEditRow();
            }
        }, {
            name: '删除',
            title: '删除',
            fun: function (e) {
                e.currentTarget.parentNode.style.display = "none";
                SharedDocumentDeleteRow();
            }
        }];

        $('.DocumentIconTD').contextMenu(sharedSpaceMenu, { onOpen: OnMeunOpen });
        $('.SharedSpaceFileNameTD').contextMenu(sharedSpaceMenu, { onOpen: OnMeunOpen });
        $('.SharedSpaceCreatedByTD').contextMenu(sharedSpaceMenu, { onOpen: OnMeunOpen });
        $('.SharedSpaceModifyDateTD').contextMenu(sharedSpaceMenu, { onOpen: OnMeunOpen });
        $('.SharedSpaceFileSizeTD').contextMenu(sharedSpaceMenu, { onOpen: OnMeunOpen });        

        var sharedDocumentPageScope = document.getElementById("SharedDocumentPageScope");
        if (globalConfig.SharedDocuments.startIndex == 0 && globalConfig.SharedDocuments.endIndex < 0) {
            sharedDocumentPageScope.innerText = "0-0";
        }
        else {
            sharedDocumentPageScope.innerText = (globalConfig.SharedDocuments.startIndex + 1) + "-" + (globalConfig.SharedDocuments.endIndex + 1);
        }


        var trNodes = document.querySelectorAll(".SharedDocumentRow");
        for (var i = 0; i < trNodes.length; i++) {
            var trNode = trNodes[i];
            trNode.onclick = function () {
                clickSharedDocumentRow(this);
            }
        }
    }

    function CreateSharedDocumentRow(sharedDocument, sharedDocumentTable) {   
        var row = sharedDocumentTable.insertRow(0);
        row.documentRowId = sharedDocument.documentRowId;
        row.fileUrl = GetSiteUrl()  + sharedDocument.fileUrl;
        row.className = "SharedDocumentRow";

        var documentIconTD = row.insertCell(0);
        var sharedSpaceFileNameTD = row.insertCell(1);
       // var sharedSpaceMenuTD = row.insertCell(2);
        var sharedSpaceCreatedByTD = row.insertCell(2);
        var sharedSpaceModifyDateTD = row.insertCell(3);
        var sharedSpaceFileSizeTD = row.insertCell(4);        

        documentIconTD.className = "DocumentIconTD";
        var documentIcon = document.createElement("img");       
        documentIcon.src = GetInconUrl(sharedDocument.icon);
        documentIconTD.appendChild(documentIcon);

        sharedSpaceFileNameTD.className = "SharedSpaceFileNameTD";
        sharedSpaceFileNameTD.innerHTML = sharedDocument.fileName;

        var fileNameLength = fucCheckLength(sharedDocument.fileName);
        if (fileNameLength > 27) {
            sharedSpaceFileNameTD.title = sharedDocument.fileName;
            sharedSpaceFileNameTD.innerHTML = AddEllipsis(sharedDocument.fileName, 27);
        }

//        sharedSpaceMenuTD.className = "SharedSpaceMenuTD";
//        var sharedSpaceMenuSpan = document.createElement("Div");
//        sharedSpaceMenuSpan.className = "SharedSpaceMenuSpan";
//        sharedSpaceMenuSpan.innerHTML = "...";
//        sharedSpaceMenuSpan.title = "打开菜单";
//        sharedSpaceMenuTD.appendChild(sharedSpaceMenuSpan);

        sharedSpaceCreatedByTD.className = "SharedSpaceCreatedByTD";
        sharedSpaceCreatedByTD.innerHTML = sharedDocument.author;      
         var authorLength = fucCheckLength(sharedDocument.author);
         if (authorLength > 10) {
             sharedSpaceCreatedByTD.Title = sharedDocument.author;
             sharedSpaceCreatedByTD.innerHTML = AddEllipsis(sharedDocument.author, 10); 
         }

        sharedSpaceModifyDateTD.className = "SharedSpaceModifyDateTD";
        sharedSpaceModifyDateTD.innerHTML = sharedDocument.lastModifyDate;

        sharedSpaceFileSizeTD.className = "SharedSpaceFileSizeTD";
        sharedSpaceFileSizeTD.innerHTML = sharedDocument.fileSize;
    }
    function onFailureForQuerySharedDocuments(sender, args) {       
            alert('查询会议记录错误：' + args.get_message());
    }
    
    function OnMeunOpen(data, e) {
        if (e.currentTarget && e.currentTarget.parentNode) {
            var rowNode = e.currentTarget.parentNode;
            if (rowNode.tagName == 'TR') {
                clickSharedDocumentRow(rowNode);
            }
        }
        var menus = document.querySelectorAll(data.menu.selector + " li");
        for (var index = 0; index < menus.length; index++) {
            if (menus[index].classList.contains("hidden")) {
                menus[index].classList.remove("hidden");
            }
        }

        var currentRow = getSharedDocumentCurrentSelectedRow();
        var documentID = currentRow.documentRowId
        var currentDocument = GetDocumentByID(documentID);
        if (currentDocument) {
            if (currentDocument.authorId == globalConfig.currentUserId || globalConfig.isAdmin) {
                // do nothing
            }
            else {  // hide edit and delete menu
                var hiddenMenu = document.querySelector(data.menu.selector + " li[title='编辑']");
                hiddenMenu.setAttribute("class", "hidden");

                hiddenMenu = document.querySelector(data.menu.selector + " li[title='删除']");
                hiddenMenu.setAttribute("class", "hidden");
                data.deltaHeight = 24.4 * 2;
            }
        }
    }

    function LoadContentMenu() {     
    
    }

    function GetDocumentByID(documentID) {
        for (var index = 0; globalConfig.SharedDocuments.documents.length; index++) {
            if (globalConfig.SharedDocuments.documents[index].documentRowId == documentID) {
                return globalConfig.SharedDocuments.documents[index];
            }
        }

        return null;
    }


    function SearchSharedSpaceDocuments() {
        var searchInput = document.getElementById("SearchInputForShareSpace");
        var searchText = searchInput.value;
        if (searchText == null || searchText == "" || searchText.Trim() == "") {
            RefreshDataForSharedSpace(false, searchText.Trim());
        }
        else {
            RefreshDataForSharedSpace(true, searchText.Trim());
            var lastSearchLink = document.getElementById("LastSearchLink");
            lastSearchLink.innerText = "搜索:" + searchText.Trim();
            lastSearchLink.onclick = function () {
                $("#SearchInputForShareSpace").val(searchText.Trim());
                RefreshDataForSharedSpace(true, searchText.Trim());
            };            
        }
    }

    function ShareDocuments() {
        this.totalRecords = 0;
        this.documents = new Array();
        this.recordPageSzie = 30;
        this.currentPage = 1;
        this.searchText = null;
        this.startIndex = 0;
        this.endIndex = 0;

        this.canMoveNextPage = function () {
            var modValue = this.totalRecords % this.recordPageSzie > 0 ? 1 : 0;
            var totalPages = Math.floor(this.totalRecords / this.recordPageSzie) + modValue;

            return this.currentPage < totalPages;
        }

        this.canMovePreviousPage = function () {
            return this.currentPage > 1;
        }

        this.moveNextPage = function () {
            if (this.canMoveNextPage()) {
                this.startIndex = this.recordPageSzie * this.currentPage;
                this.currentPage++;
                if (this.canMoveNextPage()) {
                    this.endIndex = this.recordPageSzie * this.currentPage - 1;
                }
                else {
                    this.endIndex = this.totalRecords -1;
                }
            }
        }

        this.movePreviousPage = function () {
            if (this.canMovePreviousPage()) {
                this.currentPage--
                this.endIndex = this.recordPageSzie * this.currentPage - 1;               ;
                this.startIndex = this.recordPageSzie * (this.currentPage -1);
            }
        }
    }

    function clickSharedDocumentRow(trNode) {
        var currentRow = trNode;
        if (!currentRow.classList.contains("SelectedSharedSpaceRow")) {
            var trNodes = document.querySelectorAll(".SharedDocumentRow");
            for (var i = 0; i < trNodes.length; i++) {
                var trNode = trNodes[i];
                if (trNode != currentRow && trNode.classList.contains("SelectedSharedSpaceRow")) {
                    trNode.classList.remove("SelectedSharedSpaceRow");
                }
            }

            currentRow.classList.add("SelectedSharedSpaceRow");
        }
    }

    function getSharedDocumentCurrentSelectedRow() {
        var currentRow =document.querySelector(".SelectedSharedSpaceRow");
        while (!currentRow) {
            currentRow = document.querySelector(".SelectedSharedSpaceRow");
        }

        return currentRow;
    }

    var removedDocument;
    function SharedDocumentDeleteRow() {
        var currentRow = getSharedDocumentCurrentSelectedRow();
        var result = window.confirm("确认要删除该文档吗？(不能恢复)");
        if (result == true) {
            var clientContext = new SP.ClientContext();
            var web = clientContext.get_web();
            var documentList = web.get_lists().getByTitle(globalConfig.shareDocumentsName);
            removedDocument = documentList.getItemById(currentRow.documentRowId);
            removedDocument.deleteObject();
            clientContext.executeQueryAsync(Function.createDelegate(this, this.onDeleteSharedDocumentSuccessed), Function.createDelegate(this, this.onDeleteRecordFailed));
        }
    }

    function onDeleteSharedDocumentSuccessed() {
        RefreshDataForSharedSpace();
    }

    function SharedDocumentEditRow() {
        var currentRow = getSharedDocumentCurrentSelectedRow();
        var updateUrl = globalConfig.currentWebUrl + "/Documents/Forms/EditForm.aspx?ID=" + currentRow.documentRowId + "&Source=" + document.location.href;
        openDialogForSharedDocument(updateUrl, "修改文档");
    }

    function SharedDocumentOpenRow() {
        var currentRow = getSharedDocumentCurrentSelectedRow();
        window.open(currentRow.fileUrl);
    }

    var iconKey = ['accdb','accdt','accdc','accde','accdr','asax','ascx','asmx','asp','aspx','bmp','cat','chm','config','css','db','dib','disc','doc','docm','docx','dot','dotm','dotx','dvd','dwp','dwt','eml','est','fwp','gif','hdp','hlp','hta','htm','html','htt','inf','ini','jfif','jpe','jpeg','jpg','js','jse','log','master','mht','mhtml','mpd','mpp','mps','mpt','mpw','mpx','msg','msi','msp','ocx','odc','odp','odt','ods','one','onepkg','onetoc2','pdf','png','pot','potm','potx','ppa','ppam','ppt','pptm','pptx','pps','ppsdc','ppsm','ppsx','psp','psd','ptm','ptt','pub','rdl','rsapplication','rsc','rsd','rsds','rtf','smdl','stp','stt','thmx','tif','tiff','txt','vbe','vbs','vdw','vdx','vsd','vsdm','vsdx','vsl','vss','vst','vsu','vsw','vsx','vtx','wdp','webpart','wm','wma','wmd','wmp','wms','wmv','wmx','wmz','wsf','xla','xlam','xls','xlsb','xlsm','xlsx','xlt','xltb','xltm','xltx','xml','xps','xsd','xsl','xsn','xslt','zip'];
    var iconFileName = ['icaccdb.gif','icaccdb.gif','icaccdb.gif','icaccde.gif','icaccde.gif','icasax.gif','icascx.gif','icasmx.gif','ichtm.gif','ichtm.gif','icbmp.gif','iccat.gif','icchm.gif','icconfig.gif','iccss.gif','icdb.gif','icdib.gif','icdisc.gif','icdoc.png','icdocm.png','icdocx.png','icdot.png','icdotm.png','icdotx.png','icdvd.gif','icdwp.gif','icdwt.gif','iceml.gif','icest.gif','icfwp.gif','icgif.gif','ichdp.gif','ichlp.gif','ichta.gif','ichtm.gif','ichtm.gif','ichtt.gif','icinf.gif','icini.gif','icjfif.gif','icjpe.gif','icjpeg.gif','icjpg.gif','icjs.gif','icjse.gif','iclog.gif','icmaster.gif','icmht.gif','icmht.gif','icmpd.gif','icmpp.gif','icmps.gif','icmpt.gif','icmpw.gif','icmpx.gif','icmsg.png','icmsi.gif','icmsp.gif','icocx.gif','icodc.gif','icodp.png','icodt.png','icods.png','icone.png','iconp.png','icont.png','icpdf.png','icpng.gif','icpot.png','icpotm.png','icpotx.png','icppa.png','icppam.png','icppt.png','icpptm.png','icpptx.png','icpps.png','icppsdc.png','icppsm.png','icppsx.png','icpsp.gif','icbmp.gif','icptm.gif','icptt.gif','icpub.gif','doc_sp16.gif','newreport_sp.gif','component_sp16.gif','dataset_sp16.gif','datasource.gif','icrtf.gif','model_sp16.gif','icstp.gif','icstt.gif','icthmx.gif','ictif.gif','ictiff.gif','ictxt.gif','icvbe.gif','icvbs.gif','icvdw.gif','icvdx.gif','icvsd.gif','icvsdm.gif','icvsdx.gif','icvsl.gif','icvss.gif','icvst.gif','icvsu.gif','icvsw.gif','icvsx.gif','icvtx.gif','ichdp.gif','icdwp.gif','icwm.gif','icwma.gif','icwmd.gif','icwmp.gif','icwms.gif','icwmv.gif','icwmx.gif','icwmz.gif','icwsf.gif','icxla.png','icxlam.png','icxls.png','icxlsb.png','icxlsm.png','icxlsx.png','icxlt.png','icxltx.gif','icxltm.png','icxltx.png','icxml.gif','icxps.gif','icxsd.gif','icxsl.gif','icxsn.gif','icxslt.gif','iczip.gif'];
  
    function GetInconUrl(key) {
        var index = iconKey.indexOf(key);
        if (index != -1) {
            return GetSiteUrl() + "/_layouts/images/" + iconFileName[index];
        }
        else {
            return GetSiteUrl() + "/_layouts/images/icgen.gif";
        }
    }



    $(document).ready(function () {
        $(document).bind("contextmenu", function (e) {
            return false;
        });
    });